package com.hongding.sealcenter.service.impl;

import com.hongding.sealcenter.enums.SignAlgEnum;
import com.hongding.sealcenter.helper.CAHelper;
import com.hongding.sealcenter.service.TestService;
import com.hongding.sealcenter.util.FileUtils;
import com.hongding.sealcenter.vo.ApplyPfxVo;
import com.hongding.sealcenter.vo.CACertificateVO;
import com.hongding.sealcenter.vo.PkcsVO;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;

@Service
public class TestServiceImpl implements TestService {
    @Override
    public void applyPfxCert(ApplyPfxVo vo, HttpServletResponse response) {
        createCert(vo, response);
    }

    /**
     * 封装申请证书信息
     *
     * @param vo 证书信息
     */
    private CACertificateVO getCaCertificateVO(ApplyPfxVo vo) {
        CACertificateVO caCertificateVO = new CACertificateVO();
        if (SignAlgEnum.equalsSM2(vo.getAlgorithm())) {
            caCertificateVO.setSignAlgEnum(SignAlgEnum.SM2);
        } else {
            caCertificateVO.setSignAlgEnum(SignAlgEnum.RSA);
        }
        caCertificateVO.setApplyName(vo.getName());
        caCertificateVO.setPhone(vo.getMobile());
        caCertificateVO.setEmail(vo.getEmail());
        caCertificateVO.setUnit(vo.getName());
        caCertificateVO.setApplyCardNo(vo.getIdCardNumber());
        caCertificateVO.setCertDay(vo.getExpYear()*365);
        caCertificateVO.setCaType("zjca");
        // c=cn 中国固定值 ou:部门名称 cn：证书持有者名称  sn:证书序列号，用于标识证书版本或实例
        String dn = "C=CN" + ",OU=" + vo.getName() +
                ",CN=" + vo.getName() +
                ",SN=" + vo.getIdCardNumber();
        caCertificateVO.setDn(dn);
        return caCertificateVO;
    }



    /**
     * 下载自建证书
     *
     * @param vo 证书信息
     */
    private void createCert(ApplyPfxVo vo, HttpServletResponse response) {
        //拼接证书参数
        CACertificateVO caCertificateVO = getCaCertificateVO(vo);
        PkcsVO pkcsVO = CAHelper.singleCertificate(caCertificateVO, vo.getPassword());


        //进行下载
        FileUtils.setAttachmentResponseHeader(response, vo.getName());
        byte[] decode = Base64.getDecoder().decode(pkcsVO.getPkcs12());
        try {
            response.getOutputStream().write(decode);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
